const baseUrl = 'https://pcapi-xiaotuxian-front-devtest.itheima.net'
import { useMemberStore } from '@/stores'

// 添加拦截器
const memberStore = useMemberStore()
const httpInterceptor = {
  // 请求拦截器,拦截前触发
  invoke(options: UniApp.RequestOptions) {
    // 统一添加请求域名
    if (!options.url.startsWith('http')) options.url = baseUrl + options.url

    // 设置超时时间
    options.timeout = 100000
    // 统一添加请求头
    options.header = {
      ...options.header,
      'source-client': 'miniapp',
    }
    //添加token

    const token = memberStore.profile?.token
    if (token) options.header.Authorization = token
  },
}
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)
// 请求返回数据类型
interface Data<T> {
  code: string
  msg: string
  result: T
}
export const http = <T>(options: UniApp.RequestOptions) => {
  return new Promise<Data<T>>((resolve, reject) => {
    uni.request({
      ...options,
      // 有网，不管请求成功失败，都返回数据
      success: (res) => {
        // 请求成功
        if (res.statusCode >= 200 && res.statusCode < 300)
          resolve(res.data as Data<T>)
        // 登录失效,权限问题,跳转登录
        else if (res.statusCode === 401) {
          memberStore.clearUserInfo()
          memberStore.clearProfile()
          uni.navigateTo({
            url: '/pages/login/login',
          })
          reject(res)
        } else {
          uni.showToast({
            title: (res.data as Data<T>).msg || '请求失败',
            icon: 'error',
          })
        }
      },
      // 没网或者服务器错误，返回错误信息
      fail: (err) => {
        // 请求失败
        reject(err)
      },
    })
  })
}
